package com.lsh.service.impl;

import com.lsh.dao.UserDao;
import com.lsh.dao.UserDatumDao;
import com.lsh.dao.UserHeadPortraitDao;
import com.lsh.domain.UserDatum;
import com.lsh.exception.SysException;
import com.lsh.service.HomeService;
import com.lsh.util.Base64toFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    UserDao userDao;
    @Autowired
    UserDatumDao userDatumDao;
    @Autowired
    UserHeadPortraitDao userHeadPortraitDao;

    /**
     * 获取用户所展示信息
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> showUser(Integer userId) throws SysException {
        UserDatum userDatum = userDatumDao.getByUserId(userId);
        String headPortrait = userHeadPortraitDao.getURL(userId);
        if(userDatum == null) throw new SysException("数据访问失败");
        String address = userDatum.getAddress();
        if(address.matches("[\\u4e00-\\u9fa5]+ [\\u4e00-\\u9fa5]+")){
            String[] arrays = address.split(" ");
            userDatum.setProvince(arrays[0]);
            userDatum.setCity(arrays[1]);
        }
        Map map = new HashMap();
        map.put("userDatum", userDatum);
        map.put("headPortrait", headPortrait);
        return map;
    }



    /**
     * 修改用户基本信息
     * @param userDatum
     * @throws SysException
     */
    @Override
    public void updateUserDatum(UserDatum userDatum) throws SysException {
        userDatum.setAddress(userDatum.getProvince() + " " + userDatum.getCity());
        int result = userDatumDao.updateUserDatum(userDatum);
        if(result != 1) throw new SysException("数据库操作失败");
    }

    /**
     * 修改用户备注
     * @param remark
     * @param userId
     */
    @Override
    public void updateRemark(String remark, String userId) throws SysException {
        int result = userDatumDao.updateRemark(remark, userId);
        if(result != 1) throw new SysException("数据库操作失败");
    }

    /**
     * 上传(保存)头像
     * @param userId
     * @param dirname
     * @param headImg
     * @throws SysException
     */
    @Override
    public void saveHeadPortrait(Integer userId, String dirname, String url, String headImg) throws SysException {
        String dirname2 = "/BlogImg/head/";
        dirname += dirname2;
        String filename = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        Base64toFileUtil.Base64toFile(dirname, filename, headImg);
        url += dirname2 + filename;
        int result = userHeadPortraitDao.updateHeadPortrait(userId, url);
        if(result != 1) throw new SysException("头像保存失败");
    }

}
